package com.demo.config.swagger;

import com.demo.commons.constant.ConStantsR;
import com.demo.commons.constant.HttpStatusR;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

import static com.google.common.collect.Lists.newArrayList;

/**
 *@author zwy
 *@date 2023/8/9 2:22
*/
@Configuration
@EnableSwagger2
@Profile({"dev","test"})
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        List<ResponseMessage> responseMessageList = new ArrayList<>();
        responseMessageList.add(new ResponseMessageBuilder().code(HttpStatusR.SUCCESS).message("成功").responseModel(new ModelRef("ApiError")).build());
        responseMessageList.add(new ResponseMessageBuilder().code(HttpStatusR.FORBIDDEN).message("登录过期").responseModel(new ModelRef("ApiError")).build());
        responseMessageList.add(new ResponseMessageBuilder().code(HttpStatusR.ERROR).message("通用错误").responseModel(new ModelRef("ApiError")).build());
        return new Docket(DocumentationType.SWAGGER_2)
                .globalResponseMessage(RequestMethod.GET, responseMessageList)
                .globalResponseMessage(RequestMethod.POST, responseMessageList)
                .globalResponseMessage(RequestMethod.PUT, responseMessageList)
                .globalResponseMessage(RequestMethod.DELETE, responseMessageList)
                .apiInfo(apiInfo())
                .select()
                //加了ApiOperation注解的类，才生成接口文档
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                //包下的类，才生成接口文档
//                .apis(basePackage("com.api.sys.controller,com.api.wxaliutils.wx"))
                .apis(basePackage("com.demo.sys.controller"))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(security());
    }

    /**
     * Predicate that matches RequestHandler with given base package name for the class of the handler method.
     * This predicate includes all request handlers matching the provided basePackage
     *
     * @param basePackage - base package of the classes
     * @return this
     */
    public static Predicate<RequestHandler> basePackage(final String basePackage) {
        return new Predicate<RequestHandler>() {
            @Override
            public boolean apply(RequestHandler input) {
                return declaringClass(input).transform(handlerPackage(basePackage)).or(true);
            }
        };
    }

    /**
     * 处理包路径配置规则,支持多路径扫描匹配以逗号隔开
     *
     * @param basePackage 扫描包路径
     * @return Function
     */
    private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
        return new Function<Class<?>, Boolean>() {
            @Override
            public Boolean apply(Class<?> input) {
                for (String strPackage : basePackage.split(",")) {
                    boolean isMatch = input.getPackage().getName().startsWith(strPackage);
                    if (isMatch) {
                        return true;
                    }
                }
                return false;
            }
        };
    }

    /**
     * @param input RequestHandler
     * @return Optional
     */
    private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("项目名称-接口文档")
                .description("<span style='color:red;font-size:26px;'>" +
                        "api文档说明：" +
                        "</br>&nbsp;&nbsp;1.所有返回接口中都包含基础字段code,msg,data;" +
                        "</br>&nbsp;&nbsp;2.列表格式的数据(无论是否分页)，文档中均包含基础字段code,msg,data;" +
                        "</br>&nbsp;&nbsp;3.非列表格式数据，文档中显示为data字段中含有的内容;" +
                        "</br>&nbsp;&nbsp;4.其中data内容可能为空或者结果对象，如：data:\"\"或&nbsp;data:{\"token\":\"123456\"}或&nbsp;data:[]" +
                        "</span>")
                .termsOfServiceUrl("*")
                .version("1.0.0")
                .build();
    }

    private List<ApiKey> security() {
        return newArrayList(
                // keyname 只能是英文
                new ApiKey(ConStantsR.USER_TOKEN, ConStantsR.USER_TOKEN, "header")
        );
    }
}
